#include "token.h"
#include "input.h"
#include "stateMachine.h"
#include "state.h"
#include "lex.h"


Token Lex::getNextToken()
{
	int ch;
	
	if (TOKEN_NONE != _svToken) {
	    Token temp = _svToken;
	    _svToken = TOKEN_NONE;
	    return temp;
	}    
	
	_outStream.reset();
	_stMac.initState();
	
	while (true) {
		ch = _stream.getc();
		if (ch == EOF) {
		    if (_stMac.atInitState())
		          return TOKEN_END_OF_STREAM;
            else {
                  ch = '\n';
                  _svToken = TOKEN_END_OF_STREAM;
            }    
		}		

		if(!_stMac.accept(_outStream, _stream, ch)) {
			_stream.ungetc(ch);
			break;
		}
	}

	if (!_outStream.write('\0'))
		printf("Write Char Error!");

	return _stMac.getToken(); 
}
 

const char *Lex::getCurrLexme() const
{
	return _outStream.getStr();
}


/*
int main(int argc, char *argv[])
{
	Lex lex;
	if (argc < 2)
	    return -1;
	    
	if (!lex.loadFile(argv[1])) {
		fprintf(stderr, "Load File Error!");
		return -1;
	}

	Token token;
	token = lex.getNextToken();
	while (token != TOKEN_END_OF_STREAM) {
	    printf("%7s    ", getTokenName(token));
		puts(lex.getCurrLexme());
		token = lex.getNextToken();
	}
	
	system("pause");
	return 0;
}
*/

